﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using crm_dal.Objects;
using crm_library.Javascript;
using crm_library.Extenstions;

namespace crm_web.DataPages
{
    public partial class EditSaleItem : System.Web.UI.Page
    {
        crm_dal.Objects.SaleItem displaySaleItem;

        protected void Page_Init(object sender, EventArgs e)
        {
			if (!IsPostBack)
			{
				ddlSaleID.Items.AddRange(crm_dal.Objects.Sale.GetAll().Select(item => item.ToListItem()).ToArray());
				ddlProductID.Items.AddRange(crm_dal.Objects.Product.GetAll().Select(item => item.ToListItem()).ToArray());
			}

            try
            {
                displaySaleItem = new crm_dal.Objects.SaleItem(Convert.ToInt32(HttpContext.Current.Session["Selection"]));

				ddlProductID.SelectByValue(displaySaleItem.ProductID);
				ddlSaleID.SelectByValue(displaySaleItem.SaleID);

                txtQuantity.Text = displaySaleItem.Quantity.ToString();
                txtPrice.Text = displaySaleItem.Price.ToString();


            }
            catch (Exception ex)
            {
                Alert.Show(ex.Message, Alert.AlertMessageType.Error);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string error = "";
            try
            {
				displaySaleItem.ProductID = Convert.ToInt32(ddlProductID.SelectedValue);
				displaySaleItem.SaleID = Convert.ToInt32(ddlSaleID.SelectedValue);
                displaySaleItem.Quantity = Convert.ToInt32(txtQuantity.Text);
                displaySaleItem.Price = Convert.ToDecimal(txtPrice.Text);
                
                displaySaleItem.Update();
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            if (!String.IsNullOrWhiteSpace(error))
            {
                Alert.Show(error, Alert.AlertMessageType.Error);
            }
            else
            {
                Alert.Show("edit succeeded", Alert.AlertMessageType.Message, "/DataPages/SaleItem.aspx");
            }
        }
    }
}